package com.hkts.management.upload.utils;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassNameUploadUtils
 * @Description
 * @Author yck
 * @Date2021-04-22 14:24
 * @Version V1.0
 **/

@Slf4j
@Component
public class UploadUtils {
    @Value("${transportation.uploadType}")
    private String uploadType;
    @Autowired
    private QiniuUtil qiniuUtil;

    /*
     * 根据上传配置进行判断用那种上传方式
     * */
    public  String uploadFile(MultipartFile file){
        String oldName = file.getOriginalFilename();
        //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
        String newName = IDUtils.genImageName();
        assert oldName != null;
        newName = newName + oldName.substring(oldName.lastIndexOf("."));
        //1.3生成文件在服务器端存储的子目录
        String filePath = new DateTime().toString("/yyyyMMdd/");
        //2、把图片上传到图片服务器
        //2.1获取上传的io流
        InputStream input = null;
        try {
            input = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String iamgePath="";
        if(uploadType.equals("ftp")){
            iamgePath = FtpUtil.putImages(input, filePath, newName);
        }else if(uploadType.equals("qiniu")){
            iamgePath = qiniuUtil.qiniuInputStreamUpload(input, newName);
        }

        return  iamgePath;
    }

    /*
     * 删除文件
     * */

    public void deleteFile(String filePath){
        if(uploadType.equals("ftp")){
            FtpUtil.delImages(filePath);
        }else{

        }

    }
}